#encoding:utf8
from django import forms
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from web.forms import *

def login_view(request):    #登录 页面
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        if username and password:
            user = authenticate(username=username,password=password)
            if user is not None:
                login(request,user)
                return HttpResponseRedirect('/')
            else:
                errorinfo = '错误的用户名或密码'
        else:
            errorinfo = '用户名或密码不能为空'
        return render_to_response('login.html',locals())
    return render_to_response('login.html',{})

def logout_view(request):   #注销 操作
    logout(request)
    return HttpResponseRedirect('/login')


def register(request):    #添加用户 页面
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect('/')
    else:
        form = UserCreationForm()
    return render_to_response('userregister.html',locals())

def chpasswd(request):    #更新密码  页面
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            oldpasswd = request.POST['oldpasswd']
            newpasswd = request.POST['newpasswd']
            username = request.user
            user = authenticate(username=username,password=oldpasswd)
            if user is not None:
                u = User.objects.get(username__exact=username)
                u.set_password(newpasswd)
                u.save()
                logout(request)
                return HttpResponseRedirect('/login')
            else:
                form.errors['oldpasswd'] = [u'原密码错误。']
    else:
        form = UserForm()
    return render_to_response('userchpasswd.html',locals())

